from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

# Create your views here.


# 使用内值jwt提供的认证类局部使用
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

# 内置权限类
from rest_framework.permissions import IsAuthenticated


# 只有登录用户才能访问 headers里加Authorization:JWT token值
from rest_framework_jwt.utils import jwt_decode_handler


class Order(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]
    # 权限控制
    permission_classes = [IsAuthenticated, ]
    # 有了权限和认证 只有登录才能访问

    def get(self, request, *args, **kwargs):
        return Response('这是订单信息')


# 游客登录能访问  可以不携带token jwt
# 可以通过认证类:JSONWebTokenAuthentication和权限类IsAuthenticated,来控制用户登陆以后才能访问某些接口
# 如果用户不登录就可以访问，只需要把权限类IsAuthenticated注释掉
class UserInfoAPIView(APIView):
    authentication_classes = [JSONWebTokenAuthentication, ]

    def get(self, request, *args, **kwargs):
        return Response('UserInfoAPIView')


from app02.utils import MyJwtAuthentication, MyJwtAuthentication2


class GoodsInfoAPIView(APIView):
    # authentication_classes = [MyJwtAuthentication, ]
    authentication_classes = [MyJwtAuthentication2, ]

    def get(self, request, *args, **kwargs):
        print(request.user)
        return Response('商品信息')


# 手动签发token，完成多方式登录
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from app02 import ser


class Login2View(ViewSet):

    def login(self, request, *args, **kwargs):
        """
        这是登录接口，不写成post了，直接写成login
        :param request:
        :return:
        """
        login_ser = ser.LoginModelSerializer(data=request.data, context={'request': request})  # 使用context来进行上下文交互
        # 1.需要有一个序列化的类
        # 2.生成序列化类对象
        # 3.调用序列化对象的is_valid
        login_ser.is_valid(raise_exception=True)  # 一定会走序列化类的validate方法
        token = login_ser.context.get('token')
        # 4.return token
        return Response({'status': 100, 'msg': '登录成功', 'token': token, 'username': login_ser.context.get('user')})